package com.bango.nokia.java;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;

import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;

class BangoDatabaseStorage
{
	private RecordStore _eventStore;

	private String EventTableName()
	{
		return BangoConstants.DATABASE_TABLENAMEPREFIX + "_" + Integer.toString(BangoConstants.DATABASE_VERSION);
	}

	BangoDatabaseStorage()
	{
	}

	void CloseRecordStore()
	{
		try
		{
			_eventStore.closeRecordStore();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	void OpenRecordStore()
	{
		try
		{
			_eventStore = RecordStore.openRecordStore(EventTableName(), true);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	boolean WriteRecord(String strJSON)
	{
		OpenRecordStore();
		synchronized (_eventStore)
		{
			try
			{
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				DataOutputStream dos = new DataOutputStream(baos);
				dos.writeUTF(strJSON);
				byte[] b = baos.toByteArray();
				_eventStore.addRecord(b, 0, b.length);
			}
			catch (Exception e)
			{
				return false;
			}
		}
		CloseRecordStore();
		return true;
	}

	String ReadRecord(int recordID)
	{
		String strReturn = null;
		try
		{
			ByteArrayInputStream bais = new ByteArrayInputStream(_eventStore.getRecord(recordID));
			DataInputStream dis = new DataInputStream(bais);
			strReturn = dis.readUTF();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return strReturn;
	}

	void DeleteRecord(int recordID)
	{
		try
		{
			_eventStore.deleteRecord(recordID);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	RecordEnumeration GetRecordEnumeration()
	{
		RecordEnumeration re = null;

		try
		{
			re = _eventStore.enumerateRecords(null, null, true);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return re;
	}

}
